//
//  KBTabBar.swift
//  KimboWeiBoSwift
//
//  Created by kimbo on 15/12/15.
//  Copyright © 2015年 kimbo. All rights reserved.
//

import UIKit

class KBTabBar: UITabBar {

    // MARK: - 属性
    private let count: CGFloat = 5 //子控件个数
    
    // 加号按钮点击闭包
    var compose: (() -> ())?
    
    //计算子控件位置
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let width = bounds.width / count
        
        let frame = CGRect(x: 0, y: 0, width: width, height: bounds.height)
        
        var index: CGFloat = 0
        
        for view in subviews {
            //过滤,只要UITabBarButton
            //UITabBarButton 继承UIContorl
            if view is UIControl && !(view is UIButton) {
                
                view.frame = CGRectOffset(frame, index * width, 0)
                
                index += index == 1 ? 2 : 1
            }
        }
        
        //添加中间加号按钮
        composeButton.frame = CGRectOffset(frame, width * 2, 0)
    }
    
    // MARK: - 加号按钮点击事件
    @objc private func composeButtonDidClick() {
        assert(compose != nil, "加号按钮回调闭包不能为空")
        // 执行闭包
        compose!()
    }
    
    // MARK: - 懒加载
    /* 中间加号按钮 */
    lazy var composeButton: UIButton = {
        
        let button = UIButton()
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        // 在代码块不能省略self
        self.addSubview(button)
        
        button.addTarget(self, action: "composeButtonDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    
}

